import React, { useEffect, useState } from 'react'
import { Navigate, useLocation, useMatches, useOutlet } from 'react-router'
import { Spin } from 'antd'
import { get, last } from "lodash";
import { useUserStore, useRouteStore, useTabStore } from '@/store'
import { treeFind } from '@/utils'

// 路径白名单
const WHITE_LIST = ['/login', '/test']

export default function RouteObserver({ children }) {
  // console.log('RouteObserver')
  const { token, getUserInfo, userInfo } = useUserStore()
  const { routes, filterRoutes, setActiveRoute, addCache } = useRouteStore()

  const { addTab } = useTabStore()
  /** 获取需要渲染的路由 */
  const outlet = useOutlet();
  /** 获取当前路由匹配项, 末项为当前打开的路由 */
  const matches = useMatches();
  // 获取当前路由路径
  const { pathname, search } = useLocation()
  const [loading, setLoading] = useState(true)
  const [valid, setValid] = useState(false)

  // 获取用户信息和过滤路由
  useEffect(() => {
    let fetchData = async function(){
      // console.log('fetchData')
      try {
        if (!token) return
        setLoading(true)
        // 获取用户信息和权限路由信息
        await getUserInfo()
        await filterRoutes()
        setLoading(false)
        setValid(true)
      } catch(error) {
        console.error(error)
        setLoading(false)
        setValid(false)
      }
    }
    if(!(userInfo && userInfo.userId && routes && routes.length > 0)){
      fetchData()
    } else {
      setLoading(false)
      setValid(true)
    }
  }, [token])

  // 添加当前路由到标签页和缓存路由
  useEffect(()=>{
    const fullPath = pathname + search
    // 缓存路由
    const activeRoute = last(matches);
    /** 是否需要缓存路由 */
    const keepAlive = get(activeRoute, 'handle.keepAlive', false);
    let route = treeFind(routes, route => route.path === pathname)
    // console.log('outlet', outlet)
    // console.log('matches', matches)
    // console.log('activeRoute', activeRoute)
    // console.log('keepAlive', keepAlive)
    // console.log('RouteObserver.route',routes, route)
    if(route) {
      // 缓存
      setActiveRoute(pathname);
      addCache({
        pathname,
        search,
        keepAlive,
        children: outlet
      });
      // 标签页
      addTab({
        ...route,
        pathname,
        search,
        fullPath
      })
    }
  }, [pathname, search, routes])

  // 白名单路径直接访问
  if (WHITE_LIST.includes(pathname)) {
    return children
  }

  // 如果没有token，跳转到登录页
  if (!token) {
    return <Navigate to="/login" state={{ from: location }} replace />
  }

  // 如果正在加载，显示加载中
  if (loading) {
    return (
      <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '60vh' }}>
        <Spin tip="加载中..." size="large" fullscreen/>
      </div>
    )
  }

  // 如果路由不存在，跳转到404页面
  let route = treeFind(routes, route => route.path === pathname)
  if (!route) {
    return <Navigate to="/404" replace />
  }

  // 如果出现异常,跳转到登录页面
  if (!valid) {
    return <Navigate to="/login" state={{ from: location }} replace />
  }

  return children
}
